package com.emapp.lccode.utils;

import static android.content.Context.INPUT_METHOD_SERVICE;
import static android.content.Context.TELEPHONY_SERVICE;
import static android.os.Environment.DIRECTORY_PICTURES;

import android.animation.Keyframe;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.PopupWindow;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.emapp.lccode.R;
import com.emapp.lccode.base.BaseApplication;
import com.hjq.toast.Toaster;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

public class BaseUtil {
    public static String getCurrentTime(String format) {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(format,
                Locale.getDefault());
        return dateFormat.format(date);
    }

    public static String TransTime(String time, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                Locale.getDefault());
        try {
            Date date1 = sdf.parse(time);
            SimpleDateFormat dateFormat = new SimpleDateFormat(format,
                    Locale.getDefault());// "yyyy年MM月dd HH:mm"
            return dateFormat.format(date1);
        } catch (Exception e) {
            return null;
        }
    }

    public static void hideInput(Context context, View v) {
        ((InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow
                (v.getWindowToken(), 0);
    }

    public static void fitPopupWindowOverStatusBar(PopupWindow pop, boolean needFullScreen) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                Field mLayoutInScreen = PopupWindow.class.getDeclaredField("mLayoutInScreen");
                mLayoutInScreen.setAccessible(true);
                mLayoutInScreen.set(pop, needFullScreen);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取当前版本号(注意此处获取的为3位服务器版本号)
     *
     * @param context
     * @return 当前版本号
     */
    public static final String getAppVersionForSever(Context context) {
        String version = null;
        try {
            version = getAppVersionName(context);
            String[] vs = version.split("\\.");
            if (vs.length >= 4) {
                version = vs[0] + "." + vs[1] + "." + vs[2];
            }
        } catch (PackageManager.NameNotFoundException e) {
            version = "1.0.0";
        }
        return version;
    }

    /**
     * 获取APP版本
     *
     * @param context 环境
     * @return String
     */
    public static final String getAppVersionName(Context context)
            throws PackageManager.NameNotFoundException {
        PackageManager pm = context.getPackageManager();
        PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
        return pi.versionName;
    }

    /**
     * [获取应用程序版本名称信息]
     *
     * @param context
     * @return 当前应用的版本名称
     */
    public static final int getVersionCode(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取设备唯一ID
     *
     * @return
     */
    public static String getDeviceId() {
        String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10) + (Build.CPU_ABI.length() % 10) + (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);
        String serial = null;
        try {
            serial = Build.class.getField("SERIAL").get(null).toString();
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            serial = "serial";
        }
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }

    //加
    public static String add(String v1, String v2) {
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        return b1.add(b2).toString();
    }

    //减
    public static String subtract(String v1, String v2) {
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        return b1.subtract(b2).toString();
    }

    public static float sub(String v1, String v2) {
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        return b1.subtract(b2).floatValue();
    }

    //乘
    public static String multiply(String v1, String v2) {
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        return b1.multiply(b2).toString();
    }

    //除
    public static String divide(String v1, String v2, int scale) {
        //如果精确范围小于0，抛出异常信息
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        if (b2.compareTo(BigDecimal.ZERO) == 0) {
            return "0";
        }
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).toString();
    }

    public static float divide2(int v1, int v2, int scale) {
        //如果精确范围小于0，抛出异常信息
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        if (b2.compareTo(BigDecimal.ZERO) == 0) {
            return 0;
        }
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).floatValue();
    }

    //保留小数
    public static String round(String v, int scale) {
        if (scale < 0) {
            return "0";
        }
        BigDecimal b = new BigDecimal(v);
        return b.setScale(scale, BigDecimal.ROUND_HALF_UP).toString();
    }

    public static float round2(String v, int scale) {
        if (scale < 0) {
            return 0;
        }
        BigDecimal b = new BigDecimal(v);
        return b.setScale(scale, BigDecimal.ROUND_HALF_UP).floatValue();
    }

    public static void callPhone(Context context, String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 获取指定月份最大的天数 * @param monthNum month是从1-11的,所以如果想获取5月就传4 * @return 返回最大天数
     */
    public static int getMaxDayOfMonth(int monthNum) {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.MONTH, monthNum);
        a.set(Calendar.DATE, 1);
        a.roll(Calendar.DATE, -1);
        int maxDate = a.get(Calendar.DATE);
        return maxDate;
    }

    public static String getFormatDate(int year, int month, int day) {
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
        String m = "", d = "";
        if (month < 10) {
            m = "0" + month;
        } else
            m = "" + month;
        if (day < 10) {
            d = "0" + day;
        } else
            d = "" + day;
        return year + "-" + m + "-" + d;
    }

    public static String getym(int year, int month) {
        String m = "";
        if (month < 10) {
            m = "0" + month;
        } else
            m = "" + month;
        return year + "-" + m;
    }

    public static String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    String getTime(String timeStamp) {
        if (isNull(timeStamp))
            return "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String sd = sdf.format(new Date(Long.parseLong(timeStamp + "000")));      // 时间戳转换成时间
        return sd;
    }


    public static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();
        }
        String dir = sdDir.toString();
        return dir;
    }

    public static void makeDir(File dir) {
        if (!dir.getParentFile().exists()) {
            makeDir(dir.getParentFile());
        }
        dir.mkdir();
    }

    public static boolean isCompress() {
        String BAND = Build.BRAND + "/" + Build.MODEL;
        if (BAND.equals("HUAWEI/ELE-AL00") || BAND.equals("HUAWEI/ELE-TL00") || BAND.equals("HUAWEI/VOG-AL00") || BAND.equals("HUAWEI/VOG-TL00")) {
            return false;
        } else
            return true;
    }

    public static void copy(String data) {
        ClipboardManager clipboard = (ClipboardManager) BaseApplication.instance.getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据）,其他的还有
        // newHtmlText、
        // newIntent、
        // newUri、
        // newRawUri
        ClipData clipData = ClipData.newPlainText(null, data);

        // 把数据集设置（复制）到剪贴板
        clipboard.setPrimaryClip(clipData);

    }

    /**
     * 字符串的日期格式的计算
     */

    public static int daysBetween(String smdate, String bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar cal = Calendar.getInstance();

        cal.setTime(sdf.parse(smdate));

        long time1 = cal.getTimeInMillis();

        cal.setTime(sdf.parse(bdate));

        long time2 = cal.getTimeInMillis();

        long between_days = (time2 - time1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(between_days));

    }

    /**
     * 跳转高德地图
     *
     * @param context
     * @param latitude
     * @param longtitude
     * @param address
     * @return
     */
    public static boolean goGaodeMap(Context context, double latitude, double longtitude, String address) {
        if (BaseUtil.isAppInstalled(context, "com.autonavi.minimap")) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            Uri uri = Uri.parse("androidamap://navi?sourceApplication=appname&amp;poiname=" + address + "&lat=" + latitude
                    + "&lon=" + longtitude + "&dev=1" + "&style=2");
            intent.setData(uri);
            context.startActivity(intent);
//            try {
//                Intent intent = Intent.getIntent("androidamap://navi?sourceApplication=&poiname=" + address + "&lat=" + latitude
//                        + "&lon=" + longtitude + "&dev=0");
//                context.startActivity(intent);
//            } catch (URISyntaxException e) {
//                Log.e("goError", e.getMessage());
//            }
            return true;
        } else {
            Toast.makeText(context, "您尚未安装高德地图", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    /**
     * 跳转百度地图
     *
     * @param context
     * @param latitude
     * @param longtitude
     * @param address
     * @return
     */
    public static boolean goBaiduMap(Context context, double latitude, double longtitude, String address) {
        Map<String, Float> ll = bdEncrypt(latitude, longtitude);
        float lat = ll.get("lat");
        float lon = ll.get("lon");
        if (BaseUtil.isAppInstalled(context, "com.baidu.BaiduMap")) {
            try {
                Intent intent = Intent.getIntent("intent://map/direction?destination=latlng:" + lat + "," + lon
                        + "|name:" + address + "&mode=driving&" + "region=北京" + //
                        "&src=新疆和田#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
                context.startActivity(intent);
            } catch (URISyntaxException e) {
                Log.e("goError", e.getMessage());
            }
            return true;
        } else {
            Toast.makeText(context, "您尚未安装百度地图", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    /**
     * 打开腾讯地图
     * params 参考http://lbs.qq.com/uri_v1/guide-route.html
     *
     * @param context
     * @param slat    起点纬度
     * @param slon    起点经度
     * @param sname   起点名称 可不填（0,0，null）
     * @param dlat    终点纬度
     * @param dlon    终点经度
     * @param dname   终点名称 必填
     *                驾车：type=drive，policy有以下取值
     *                0：较快捷
     *                1：无高速
     *                2：距离
     *                policy的取值缺省为0
     *                &from=" + dqAddress + "&fromcoord=" + dqLatitude + "," + dqLongitude + "
     */
    public static boolean openTencentMap(Context context, double slat, double slon, String sname, double dlat, double dlon, String dname) {
        if (BaseUtil.isAppInstalled(context, "com.tencent.map")) {
            String uriString = null;
            StringBuilder builder = new StringBuilder("qqmap://map/routeplan?type=drive&policy=0&referer=wuczh");
            if (slat != 0) {
                builder.append("&from=").append(sname)
                        .append("&fromcoord=").append(slat)
                        .append(",")
                        .append(slon);
            }
            builder.append("&to=").append(dname)
                    .append("&tocoord=").append(dlat)
                    .append(",")
                    .append(dlon);
            uriString = builder.toString();
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setPackage("com.tencent.map");
            intent.setData(Uri.parse(uriString));
            context.startActivity(intent);
            return true;
        } else {
            Toast.makeText(context, "您尚未安装腾讯地图", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    /**
     * 打开高德地图导航功能
     *
     * @param context
     * @param slat    起点纬度
     * @param slon    起点经度
     * @param sname   起点名称 可不填（0,0，null）
     * @param dlat    终点纬度
     * @param dlon    终点经度
     * @param dname   终点名称 必填
     */
    public static boolean openGaoDeNavi(Context context, double slat, double slon, String sname, double dlat, double dlon, String dname) {
        if (BaseUtil.isAppInstalled(context, "com.autonavi.minimap")) {
            String uriString = null;
            StringBuilder builder = new StringBuilder("amapuri://route/plan?");
            if (slat != 0) {
                builder.append("sname=").append(sname)
                        .append("&slat=").append(slat)
                        .append("&slon=").append(slon);
            }
            builder.append("&dlat=").append(dlat)
                    .append("&dlon=").append(dlon)
                    .append("&dname=").append(dname)
                    .append("&dev=0")
                    .append("&t=0");
            uriString = builder.toString();
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setPackage("com.autonavi.minimap");
            intent.setData(Uri.parse(uriString));
            context.startActivity(intent);
            return true;
        } else {
            Toast.makeText(context, "您尚未安装高德地图", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    /**
     * 打开百度地图导航功能(默认坐标点是高德地图，需要转换)
     *
     * @param context
     * @param slat    起点纬度
     * @param slon    起点经度
     * @param sname   起点名称 可不填（0,0，null）
     * @param dlat    终点纬度
     * @param dlon    终点经度
     * @param dname   终点名称 必填
     */
    public static boolean openBaiDuNavi(Context context, double slat, double slon, String sname, double dlat, double dlon, String dname) {
        if (BaseUtil.isAppInstalled(context, "com.baidu.BaiduMap")) {
            String uriString = null;
            //终点坐标转换
//        此方法需要百度地图的BaiduLBS_Android.jar包
//        LatLng destination = new LatLng(dlat,dlon);
//        LatLng destinationLatLng = GCJ02ToBD09(destination);
//        dlat = destinationLatLng.latitude;
//        dlon = destinationLatLng.longitude;
            Map<String, Float> ll = bdEncrypt(dlat, dlon);
            float lat = ll.get("lat");
            float lon = ll.get("lon");
            // double destination[] = gaoDeToBaidu(dlat, dlon);
            dlat = lat;
            dlon = lon;

            StringBuilder builder = new StringBuilder("baidumap://map/direction?mode=driving&");
            if (slat != 0) {
                //起点坐标转换

//            LatLng origin = new LatLng(slat,slon);
//            LatLng originLatLng = GCJ02ToBD09(origin);
//            slat = originLatLng.latitude;
//            slon = originLatLng.longitude;

                //double[] origin = gaoDeToBaidu(slat, slon);//不准
                Map<String, Float> ll2 = bdEncrypt(slat, slon);
                float lat2 = ll2.get("lat");
                float lon2 = ll2.get("lon");
                slat = lat2;
                slon = lon2;

                builder.append("origin=latlng:")
                        .append(slat)
                        .append(",")
                        .append(slon)
                        .append("|name:")
                        .append(sname);
            }
            builder.append("&destination=latlng:")
                    .append(dlat)
                    .append(",")
                    .append(dlon)
                    .append("|name:")
                    .append(dname);
            uriString = builder.toString();
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setPackage("com.baidu.BaiduMap");
            intent.setData(Uri.parse(uriString));
            context.startActivity(intent);
            return true;
        } else {
            Toast.makeText(context, "您尚未安装百度地图", Toast.LENGTH_SHORT).show();
            return false;
        }

    }

//    /**
//     * 百度转高德
//     *
//     * @param bd_lat
//     * @param bd_lon
//     * @return
//     */
//    public static double[] bdToGaoDe(double bd_lat, double bd_lon) {
//        double[] gd_lat_lon = new double[2];
//        double PI = 3.14159265358979324 * 3000.0 / 180.0;
//        double x = bd_lon - 0.0065, y = bd_lat - 0.006;
//        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * PI);
//        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * PI);
//        gd_lat_lon[0] = z * Math.cos(theta);
//        gd_lat_lon[1] = z * Math.sin(theta);
//        return gd_lat_lon;
//    }
//
//    /**
//     * 高德、腾讯转百度
//     *
//     * @param gd_lon
//     * @param gd_lat
//     * @return
//     */
//    private static double[] gaoDeToBaidu(double gd_lon, double gd_lat) {
//        double[] bd_lat_lon = new double[2];
//        double PI = 3.14159265358979324 * 3000.0 / 180.0;
//        double x = gd_lon, y = gd_lat;
//        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * PI);
//        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * PI);
//        bd_lat_lon[0] = z * Math.cos(theta) + 0.0065;
//        bd_lat_lon[1] = z * Math.sin(theta) + 0.006;
//        return bd_lat_lon;
//    }

//    /**
//     * 判断手机中是否安装指定包名的软件
//     *
//     * @param context
//     * @param pkgname 包名
//     */
//    public static boolean isInstallApk(Context context, String pkgname) {
//        return new File("/data/data/" + pkgname).exists();
////        List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);
////        for (int i = 0; i < packages.size(); i++) {
////            PackageInfo packageInfo = packages.get(i);
////            if (packageInfo.packageName.equals(pkgname)) {
////                return true;
////            } else {
////                continue;
////            }
////        }
////        return false;
//    }

    // 返回 true 则已安装
// 返回 false 则为未安装
    private static boolean isAppInstalled(Context context, String pkgName) {
        if (pkgName == null || pkgName.isEmpty()) {
            return false;
        }
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(pkgName, PackageManager.GET_CONFIGURATIONS);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }

        if (packageInfo != null) {
            return true;
        }
        return false;
    }

    /**
     * 高德转百度
     *
     * @param gg_lat
     * @param gg_lon
     * @return
     */
    public static Map<String, Float> bdEncrypt(double gg_lat, double gg_lon) {
        double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        Map<String, Float> data = new HashMap<String, Float>();
        double x = gg_lon, y = gg_lat;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        double bd_lon = z * Math.cos(theta) + 0.0065;
        double bd_lat = z * Math.sin(theta) + 0.006;
        System.out.println(bd_lon + "," + bd_lat);
        System.out.println(new BigDecimal(String.valueOf(bd_lon)).floatValue() + "," + new BigDecimal(String.valueOf(bd_lat)).floatValue());
        data.put("lon", new BigDecimal(String.valueOf(bd_lon)).floatValue());
        data.put("lat", new BigDecimal(String.valueOf(bd_lat)).floatValue());
        return data;
    }

    /**
     * 百度转高德
     *
     * @param bd_lat
     * @param bd_lon
     * @return
     */
    public static Map<String, Double> bd_decrypt(double bd_lat, double bd_lon) {
        double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
        double x = bd_lon - 0.0065, y = bd_lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
        double gg_lon = z * Math.cos(theta);
        double gg_lat = z * Math.sin(theta);
        Map<String, Double> data = new HashMap<String, Double>();
        data.put("lon", gg_lon);
        data.put("lat", gg_lat);
        return data;
    }
// 内部存储
// /data/data/包名/files
//context.getFilesDir().getPath()
//
// /data/data/包名/cache
//context.getCacheDir().getPath()
//
// 外部存储
// /sdcard/Android/data/包名/cache/dir
//context.getExternalFilesDir("dir").getPath()
//
// /sdcard/Android/data/包名/cache
//context.getExternalCacheDir().getPath()

    /**
     * 获取应用私有file目录
     * <p>
     * /sdcard/Android/data/包名/file/dir
     *
     * @param dir The type of files directory to return. May be {@code null}
     *            for the root of the files directory or one of the following
     *            constants for a subdirectory:
     *            {@link Environment#DIRECTORY_MUSIC},
     *            {@link Environment#DIRECTORY_PODCASTS},
     *            {@link Environment#DIRECTORY_RINGTONES},
     *            {@link Environment#DIRECTORY_ALARMS},
     *            {@link Environment#DIRECTORY_NOTIFICATIONS},
     *            {@link Environment#DIRECTORY_PICTURES}, or
     *            {@link Environment#DIRECTORY_MOVIES}.
     */
    public static String getPrivateFilePath(Context context, String dir) {
        File file = context.getExternalFilesDir(dir);
        //先判断外部存储是否可用
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && file != null) {
            return file.getAbsolutePath();
        } else {
            return context.getFilesDir() + File.separator + dir;
        }
    }


    /**
     * 获取应用私有cache目录
     * <p>
     * /sdcard/Android/data/包名/cache
     */
    public static String getPrivateCachePath(Context context) {
        File file = context.getExternalCacheDir();
        //先判断外部存储是否可用
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && file != null) {
            return file.getAbsolutePath();
        } else {
            return context.getCacheDir().getAbsolutePath();
        }
    }

    public static boolean needToken(String url) {
        if (url.endsWith("/api/") || url.endsWith("register") || url.endsWith("login_proving"))
            return false;
        else
            return true;
    }

    public static int getScreenWidthPx(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int w_screen = dm.widthPixels;
        return w_screen;
    }
//    public static void base64ToVideo(String base64, String videoFilePath) {
//        Base64.decode(firstInfo.img.img.split(",")[1], Base64.DEFAULT);
//        try {
//            //base解密
//            byte[] videoByte = new sun.misc.BASE64Decoder().decodeBuffer(base64);
//            File videoFile = new File(videoFilePath);
//            //输入视频文件
//            FileOutputStream fos = new FileOutputStream(videoFile);
//            fos.write(videoByte, 0, videoByte.length);
//            fos.flush();
//            fos.close();
//        } catch (IOException e) {
//            log.info("base64转换为视频异常");
//        }
//    }

    /**
     * 生成视图的预览
     *
     * @param activity
     * @param v
     * @return 视图生成失败返回null
     * 视图生成成功返回视图的绝对路径
     */
    public static String saveImage(AppCompatActivity activity, View v) {
        Bitmap bitmap;
        String path = Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES) + "/";
        //String path = XtomFileUtil.getFileDir(activity) + "preview.png";
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        bitmap = view.getDrawingCache();
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int[] location = new int[2];
        v.getLocationOnScreen(location);
        path = path + System.currentTimeMillis() + "zhengshu.png";
        File file = new File(path);

        try {
            if (file.exists())
                file.delete();
            file.createNewFile();
            bitmap = Bitmap.createBitmap(bitmap, location[0], location[1], v.getWidth(), v.getHeight());
            FileOutputStream fout = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fout);
            fout.flush();
            fout.close();
            // }
            activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
            Toaster.show("已保存图片到手机");
            Log.e("png", "生成预览图片成功：" + path);
            return path;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.e("png", "生成预览图片失败：" + e);
        } catch (IllegalArgumentException e) {
            Log.e("png", "width is <= 0, or height is <= 0");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 清理缓存
            view.destroyDrawingCache();
        }
        return null;

    }

    public static void saveBitmapFile(AppCompatActivity activity, Bitmap bitmap) {
        String path = Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES) + "/";
        //File temp = new File(BaseUtil.getSDPath() + BaseConfig.SAVE_ROOT + "/IMAGE");//要保存文件先创建文件夹
//        makeDir(temp);
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        //重复保存时，覆盖原同名图片
        File file = new File(path + System.currentTimeMillis() + "z.jpg");//将要保存图片的路径和图片名称
        //    File file =  new File("/sdcard/1delete/1.png");/延时较长
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
            Toaster.show("保存成功");
            activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
        } catch (IOException e) {
            Toaster.show("保存失败");
            e.printStackTrace();
        }
    }

    //tada方法实现了上下抖动
    public static void tada(View view) {
        ObjectAnimator animator = tadaview(view);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.start();
    }

    public static ObjectAnimator tadaview(View view) {
        return tada(view, 1f);
    }

    public static ObjectAnimator tada(View view, float shakeFactor) {

        PropertyValuesHolder pvhScaleX = PropertyValuesHolder.ofKeyframe(View.SCALE_X,
                Keyframe.ofFloat(0f, 1f),
                Keyframe.ofFloat(.1f, .9f),
                Keyframe.ofFloat(.2f, .9f),
                Keyframe.ofFloat(.3f, 1.1f),
                Keyframe.ofFloat(.4f, 1.1f),
                Keyframe.ofFloat(.5f, 1.1f),
                Keyframe.ofFloat(.6f, 1.1f),
                Keyframe.ofFloat(.7f, 1.1f),
                Keyframe.ofFloat(.8f, 1.1f),
                Keyframe.ofFloat(.9f, 1.1f),
                Keyframe.ofFloat(1f, 1f)
        );

        PropertyValuesHolder pvhScaleY = PropertyValuesHolder.ofKeyframe(View.SCALE_Y,
                Keyframe.ofFloat(0f, 1f),
                Keyframe.ofFloat(.1f, .9f),
                Keyframe.ofFloat(.2f, .9f),
                Keyframe.ofFloat(.3f, 1.1f),
                Keyframe.ofFloat(.4f, 1.1f),
                Keyframe.ofFloat(.5f, 1.1f),
                Keyframe.ofFloat(.6f, 1.1f),
                Keyframe.ofFloat(.7f, 1.1f),
                Keyframe.ofFloat(.8f, 1.1f),
                Keyframe.ofFloat(.9f, 1.1f),
                Keyframe.ofFloat(1f, 1f)
        );

        PropertyValuesHolder pvhRotate = PropertyValuesHolder.ofKeyframe(View.ROTATION,
                Keyframe.ofFloat(0f, 0f),
                Keyframe.ofFloat(.1f, -3f * shakeFactor),
                Keyframe.ofFloat(.2f, -3f * shakeFactor),
                Keyframe.ofFloat(.3f, 3f * shakeFactor),
                Keyframe.ofFloat(.4f, -3f * shakeFactor),
                Keyframe.ofFloat(.5f, 3f * shakeFactor),
                Keyframe.ofFloat(.6f, -3f * shakeFactor),
                Keyframe.ofFloat(.7f, 3f * shakeFactor),
                Keyframe.ofFloat(.8f, -3f * shakeFactor),
                Keyframe.ofFloat(.9f, 3f * shakeFactor),
                Keyframe.ofFloat(1f, 0)
        );

        return ObjectAnimator.ofPropertyValuesHolder(view, pvhScaleX, pvhScaleY, pvhRotate).
                setDuration(1000);
    }

    //nope方法实现了左右抖动
    public static void nope(View view) {
        ObjectAnimator animator = nopeview(view);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.start();
    }

    static ObjectAnimator nopeview(View view) {
        int delta = view.getResources().getDimensionPixelOffset(R.dimen.spacing_medium);
        PropertyValuesHolder pvhTranslateX = PropertyValuesHolder.ofKeyframe(View.TRANSLATION_X,
                Keyframe.ofFloat(0f, 0),
                Keyframe.ofFloat(.10f, -delta),
                Keyframe.ofFloat(.26f, delta),
                Keyframe.ofFloat(.42f, -delta),
                Keyframe.ofFloat(.58f, delta),
                Keyframe.ofFloat(.74f, -delta),
                Keyframe.ofFloat(.90f, delta),
                Keyframe.ofFloat(1f, 0f)
        );

        return ObjectAnimator.ofPropertyValuesHolder(view, pvhTranslateX).
                setDuration(900);
    }

    /**
     * 适合播放声音短，文件小
     * 可以同时播放多种音频
     * 消耗资源较小
     */
    public static void playSound(Context context, int rawId) {
        SoundPool soundPool;
        if (Build.VERSION.SDK_INT >= 21) {
            SoundPool.Builder builder = new SoundPool.Builder();
            //传入音频的数量
            builder.setMaxStreams(1);
            //AudioAttributes是一个封装音频各种属性的类
            AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
            //设置音频流的合适属性
            attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
            builder.setAudioAttributes(attrBuilder.build());
            soundPool = builder.build();
        } else {
            //第一个参数是可以支持的声音数量，第二个是声音类型，第三个是声音品质
            soundPool = new SoundPool(1, AudioManager.STREAM_SYSTEM, 5);
        }
        //第一个参数Context,第二个参数资源Id，第三个参数优先级
        soundPool.load(context, rawId, 1);
        soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                soundPool.play(1, 1, 1, 0, 0, 1);
            }
        });
        //第一个参数id，即传入池中的顺序，第二个和第三个参数为左右声道，第四个参数为优先级，第五个是否循环播放，0不循环，-1循环
        //最后一个参数播放比率，范围0.5到2，通常为1表示正常播放
//        soundPool.play(1, 1, 1, 0, 0, 1);
        //回收Pool中的资源
        //soundPool.release();

    }

    @SuppressLint("MissingPermission")
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static String getIMEI(Context context) {
        String imei = "";
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                imei = tm.getDeviceId();
            } else {
                Method method = tm.getClass().getMethod("getImei");
                imei = (String) method.invoke(tm);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return imei;
    }


    public static byte[] getSign(Context context) {
        PackageManager pm = context.getPackageManager();

        List apps = pm.getInstalledPackages(PackageManager.GET_SIGNATURES);

        Iterator iter = apps.iterator();

        while (iter.hasNext()) {
            PackageInfo info = (PackageInfo) iter.next();
            String packageName = info.packageName;
//按包名 取签名
            if (packageName.equals("com.dmapp.yiqing")) {
                return info.signatures[0].toByteArray();

            }

        }

        return null;

    }

    public static boolean checkCarNumber(String content) {
        String pattern = "([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{1}(([A-HJ-Z]{1}[A-HJ-NP-Z0-9]{5})|([A-HJ-Z]{1}(([DF]{1}[A-HJ-NP-Z0-9]{1}[0-9]{4})|([0-9]{5}[DF]{1})))|([A-HJ-Z]{1}[A-D0-9]{1}[0-9]{3}警)))|([0-9]{6}使)|((([沪粤川云桂鄂陕蒙藏黑辽渝]{1}A)|鲁B|闽D|蒙E|蒙H)[0-9]{4}领)|(WJ[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼·•]{1}[0-9]{4}[TDSHBXJ0-9]{1})|([VKHBSLJNGCE]{1}[A-DJ-PR-TVY]{1}[0-9]{5})";
        return Pattern.matches(pattern, content);
    }

    //dip和px转换
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 读取本地的JSON 数据
     *
     * @param context
     * @param fileName
     * @return
     */
    public static String getJson(Context context, String fileName) {

        StringBuffer stringBuffer = new StringBuffer();
        try {
            AssetManager assetsManager = context.getAssets();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(assetsManager.open(fileName)));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuffer.toString();
    }

    public static final boolean isNull(String str) {
        return str == null || "".equals(str.trim());
    }
}

